package com.enation.app.javashop.core.base.context;

import com.enation.app.javashop.core.base.CachePrefix;
import com.enation.app.javashop.core.client.system.SensitiveWordsClient;
import com.enation.app.javashop.framework.cache.Cache;
import com.enation.app.javashop.framework.exception.SystemErrorCode;
import com.enation.app.javashop.framework.util.StringUtil;
import jodd.util.URLDecoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.Charset;
import java.util.List;

/**
 * @author fk
 * @version v2.0
 * @Description: 敏感词拦截
 * @date 2018/8/2 14:53
 * @since v7.0.0
 */
@Component
@WebFilter(filterName = "sensitiveWordsFilter", urlPatterns = "/*")
@Order(100)
public class SensitiveWordsFilter implements Filter {

    @Autowired
    private SensitiveWordsClient sensitiveWordsClient;

    @Autowired
    private Cache cache;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) servletRequest;

        String path = req.getServletPath();
        if (path.startsWith("/admin/sensitive-words")) {
            filterChain.doFilter(req, servletResponse);
            return;
        }

        String wholeStr = "";

        StringBuilder sb = new StringBuilder();
        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            inputStream = req.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        wholeStr = sb.toString();

        String queryString = req.getQueryString();

        if (StringUtil.isEmpty(queryString) && StringUtil.isEmpty(wholeStr)) {
            filterChain.doFilter(req, servletResponse);
            return;
        }

        queryString = queryString == null ? "" : queryString;

        queryString = URLDecoder.decode(queryString, "utf-8");

        List<String> words = (List<String>)cache.get(CachePrefix.SENSITIVE_WORDS.getPrefix());
        if(words == null){
            words = sensitiveWordsClient.listWords();
            cache.put(CachePrefix.SENSITIVE_WORDS.getPrefix(),words);
        }
        boolean flag = true;
        for (String word : words) {
            if (queryString.contains(word) || wholeStr.contains(word)) {
                flag = false;
                break;
            }
        }
        if (!flag) {
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            response.setStatus(500);

            PrintWriter out = response.getWriter();
            out.append(URLDecoder.decode("{" +
                    "  \"code\": \"" + SystemErrorCode.INVALID_COTENT + "\"," +
                    "  \"message\": \"提交内容包含广告、色情、违禁、谣言等信息\"" +
                    "}", "utf-8"));
            out.flush();
            out.close();
        }else{
            filterChain.doFilter(req, servletResponse);
        }


    }

    @Override
    public void destroy() {

    }
}
